
// 注册
import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet,
  StatusBar,
  Image,
  Alert,
  TextInput,
  Modal,
  Platform,
  PermissionsAndroid
} from 'react-native';
import {windowWidth, windowHeight, getHeight, getWidth} from '@/utils/index';
import IconFont, {IconNames} from '../../assets/iconfont';
import Touchable from '../../components/Touchable';
import TreeSelect, {LeafClickProps} from 'react-native-tree-select';
import cityData from '../../assets/cityData/city_data.json';
import Toast from 'react-native-root-toast';
// import ImagePicker from 'react-native-image-picker';
import  { launchCamera ,  launchImageLibrary }  from  'react-native-image-picker' ;
// import  { launchCamera ,  launchImageLibrary }  from  'react-native-image-picker' ;
// 连接到dva,react-redux本身充当一个桥梁的作用
import {connect, ConnectedProps} from 'react-redux';
import {RootState} from "@/models/index";
const mapStateToProps = ({users, loading}: RootState) => {
  return {
    // 在触发getUserInfo方法时加上加载效果
    loading: loading.effects['users/register'],
  };
};
// connect接受一个mapStateToProps函数，将dva的state映射成当前组件的props
const connector = connect(mapStateToProps);
type ModelState = ConnectedProps<typeof connector>;
interface IProps extends ModelState{
  navigation: {goBack: any; navigate: any};
}

interface ICityData {
  id: string;
  name: string;
  sortNo: string;
  parentId: string;
  children?: ICityData[];
}
interface ITree {
  modalVisible: boolean;
  setModalVisible: Function;
  setSaveCity: Function;
}
interface FormData {
  username:string;
  password:string;
  age:string;
  city:string;
  scurpture:string;
  nature:string;
  // 身份有两种，一个是普通用户，一个是摄影师，默认为普通用户
  identity:string;
}
const Tree = React.memo((props: ITree) => {
  const {setModalVisible, modalVisible, setSaveCity} = props;
  const onSaveCity = () => {
    console.log('点击了');
  };
  const onSaveCityLeaf = (p: LeafClickProps) => {
    setSaveCity(p.item.name);
    setModalVisible(false);
  };
  return (
    <Modal
      animationType="slide"
      transparent={true}
      visible={modalVisible}
      onRequestClose={() => {
        Alert.alert('Modal has been closed.');
        setModalVisible(!modalVisible);
      }}>
      <View style={styles.modalView}>
        <TreeSelect
          data={cityData.provinces as ICityData[]}
          // isOpen
          isShowTreeId={false}
          itemStyle={{
            fontSize: 12,
            color: '#995962',
          }}
          selectedItemStyle={{
            fontSize: 14,
            color: 'black',
          }}
          onClick={onSaveCity}
          onClickLeaf={onSaveCityLeaf}
          treeNodeStyle={{
            openIcon: (
              <Image
                resizeMode="stretch"
                style={{width: 18, height: 18}}
                source={require('../../assets/localImage/login_image.png')}
              />
            ),
            closeIcon: (
              <Image
                resizeMode="stretch"
                style={{width: 18, height: 18}}
                source={require('../../assets/localImage/login_image.png')}
              />
            ),
          }}
        />
      </View>
    </Modal>
  );
});
const Register = (props: IProps) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [saveCity, setSaveCity] = useState(null);
  const [image, setImage] = useState<{uri:string}>();
  const [formData, setFormData] = useState<FormData>({
    username:'',
    password:'',
    age:'',
    city:'',
    scurpture:'',
    nature:'',
    // 身份有两种，一个是普通用户，一个是摄影师，默认为普通用户
    identity:''
  });
  const {dispatch, navigation} = props;
  useEffect(() => {
    cityData.provinces.map((city: any, i: number) => {
      city.id = i.toString();
      city.sortNo = i.toString();
      city.parentId = i.toString();
      city.children &&
        city.children.map((cityItem: any, index: number) => {
          cityItem.id = i.toString() + '0' + index.toString();
          cityItem.sortNo = i.toString() + '0' + index.toString();
          cityItem.parentId = i.toString();
        });
    });
  }, []);
  const handlePressCity = () => {
    console.log(true);
    setModalVisible(true);
  };
  const handleAddPicCheck = () => {
    console.warn('添加图片------check');
    const options: any = {
      cameraType: 'back',
      mediaType: 'photo', // 媒体类型还可以是视频或者图片视频二者混合，默认选取一张
      videoQuality: 'high',
      durationLimit: 10,
      maxWidth: 720,
      maxHeight: 1280,
      quality: 1,
    };
    // 启动相机拍摄照片或者视频
    // launchCamera(options, (res) =>{
    //   console.log("回调")
    // });

    // // 启动图库选择照片或者视频
    // launchImageLibrary(options, res => {
    //   console.log('回调');
    // });
    async function requestCameraPermission() {
      console.log("Platform.Version",Platform.Version)
      if (Platform.Version as number >= 31) {
        // 如果运行的是 Android 12 或更高版本，选用新模型来请求相机权限
        // const result = await requestPermissionAndroid12('android.permission.CAMERA');
        // 请求本地存储权限
        const result = await requestPermissionAndroid12('android.permission.READ_EXTERNAL_STORAGE')
        if (result === PermissionsAndroid.RESULTS.GRANTED) {
          console.log("加载权限")
          // launchCamera(options, (res)=>{
          //   console.log("res",res)
          // });
          //打开图库
          launchImageLibrary(options, ({assets})=>{
            console.log("res",assets)
            // res {"assets": [{"fileName": "rn_image_picker_lib_temp_00144087-1f0f-4d10-ae39-5ad9f2a02440.jpg", "fileSize": 232251, "height": 720, "type": "image/jpeg", "uri": "file:///data/user/0/com.xipai/cache/rn_image_picker_lib_temp_00144087-1f0f-4d10-ae39-5ad9f2a02440.jpg", "width": 720}]}
            if(assets && assets[0].uri) {
              setImage({uri:assets[0].uri})
            }
          });
          console.log('Camera permission granted权限通过');
        } else {
          console.log('Camera permission denied权限拒绝');
        }
      } else {
        // 如果运行的是 Android 11 或更低版本，使用之前的版本的权限请求模型来请求
        try {
          const granted = await PermissionsAndroid.request(
            // PermissionsAndroid.PERMISSIONS.CAMERA,
            PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
            {
              title: 'App android.permission.READ_EXTERNAL_STORAGE Permission',
              message: 'App needs access to android.permission.READ_EXTERNAL_STORAGE.',
              buttonNeutral: 'Ask Me Later',
              buttonNegative: 'Cancel',
              buttonPositive: 'OK',
            },
          );
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log('Camera permission granted,11一下权限请求通过');
          } else {
            console.log('Camera permission denied,11一下权限请求失败');
          }
        } catch (err) {
          console.warn(err);
        }
      }
    }
    async function requestPermissionAndroid12(permission:any) {
      // 检查是否该应用被永久允许了相机权限android.permission.CAMERA
      const isGranted = await PermissionsAndroid.check(permission);
      if (isGranted) {
        // 如果设置的应用权限管理中用户允许了，直接返回许可令
        return PermissionsAndroid.RESULTS.GRANTED;
      }
      // 询问用户是否给权限，如果用户设置的是每次使用时询问
      const result = await PermissionsAndroid.request(permission);
      if (result === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("yunxu")
        return PermissionsAndroid.RESULTS.GRANTED;
      } else if (result === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
        throw new Error('Permission denied with never ask again');
      } else {
        throw new Error('Permission denied');
      }
    }
    
   
    requestCameraPermission()
    
  };
  const uploadEquipImg = async (params: any) => {
    let {formData} = params;
    // return await UploadRequest('自己的接口地址', formData)
  };
  const onChangeText = (text: string, name: string) => {
    console.log('name', name, 'text', text);
    let obj = {[name]: text};
    let newFormData = Object.assign(formData, obj);
    // const formData = new FormData();
    // formData.append('email', email);
    // formData.append('username', username);
    // formData.append('password', password);
    // formData.append('avatar', {
    //   uri: avatar.uri,
    //   name: 'avatar.jpg',
    //   type: 'image/jpeg',
    // });
   
    setFormData(newFormData);
  };
  const handleRegister = () => {
    console.log('点击了注册', formData);
    if (
      !saveCity ||
      !image ||
      formData.nature.trim().length === 0 ||
      formData.username.trim().length === 0 ||
      formData.password.trim().length === 0 ||
      formData.age.trim().length === 0
    ) {
      Toast.show('请把数据填写完整，选择图片作为头像再注册', {
        position: Toast.positions.CENTER,
        duration: Toast.durations.LONG,
        shadow: true,
        animation: true,
      });
      return;
    }
    let reg = /^\d+$/;
    if (!reg.test(formData.age)) {
      Toast.show('年龄必须为数字', {
        position: Toast.positions.CENTER,
        duration: Toast.durations.LONG,
        shadow: true,
        animation: true,
      });
      return;
    }
    let obj = {
      city: saveCity,
      scurpture: image.uri,
      identity: '普通用户',
    };
    let newFormData = Object.assign(formData, obj);
    console.log('newFormData', newFormData);
    dispatch({
      type: 'users/register',
      payload: {
        formData: newFormData,
        callback: (data:string) => {
          console.log("注册成功了",data);
          // 如果注册的code为200，跳转回到登录页面
          navigation.navigate('Login');
        },
      },
    })
    setFormData(newFormData);
  };
  return (
    <View style={{width: windowWidth, height: windowHeight}}>
      <View style={modalVisible ? styles.loginBox1 : styles.loginBox}>
        <StatusBar
          backgroundColor={modalVisible ? '#ccc' : '#fff'}
          barStyle="dark-content"
        />
        <Touchable
          onPress={() => {
            navigation.goBack();
          }}>
          <IconFont name="icon-fanhui" size={26} color={'#999'}></IconFont>
        </Touchable>
        <View style={styles.mainBox}>
          {!image && <Text style={styles.bigTitle}>XiPai</Text>}
          <Touchable style={styles.avatarBox} onPress={handleAddPicCheck}>
            {!image && <IconFont name="icon-jia" size={30} color={'#A75E5E'}></IconFont>}
            {!image && <Text style={styles.avatar}>请上传头像</Text>}
            {image && <Image source={image} style={styles.avatarImage} />}
          </Touchable>
          <TextInput
            onChangeText={text => onChangeText(text,"username")}
            placeholder="请输入用户名"
            style={[styles.inputBox, styles.inputBoxTop]}></TextInput>
          <TextInput
            secureTextEntry={true}
            // keyboardType='visible-password'
            onChangeText={text => onChangeText(text,"password")}
            placeholder="请输入密码"
            style={styles.inputBox}></TextInput>
          <TextInput
            // 弹出纯数字键盘，但是用户依然可以切换键盘
            keyboardType="numeric"
            onChangeText={text => onChangeText(text,"age")}
            placeholder="请输入年龄"
            style={styles.inputBox}></TextInput>
          <Touchable onPress={handlePressCity}>
            <Text style={[styles.inputBox, styles.inputBox1]}>
              {saveCity ? saveCity : '请选择常住城市'}
            </Text>
          </Touchable>
          <TextInput
            placeholder="请输入性格爱好"
            style={styles.inputBox}
            onChangeText={text => onChangeText(text,"nature")}></TextInput>
          <Touchable onPress={handleRegister}>
            <Text style={styles.registerBtn}>注册</Text>
          </Touchable>
        </View>
      </View>
      {modalVisible && (
        <View style={styles.centeredView}>
          <Tree
            modalVisible={modalVisible}
            setModalVisible={setModalVisible}
            setSaveCity={setSaveCity}></Tree>
        </View>
      )}
    </View>
  );
};
const styles = StyleSheet.create({
  loginBox: {
    padding: 10,
    backgroundColor: '#fff',
    width: windowWidth,
    height: windowHeight,
  },
  loginBox1: {
    // padding: 10,
    backgroundColor: '#ccc',
    width: windowWidth,
    height: windowHeight,
  },
  mainBox: {
    matginTop: 10,
    display: 'flex',
    alignItems: 'center',
  },
  bigTitle: {
    fontSize: 70,
    fontWeight: '700',
    color: '#A75E5E',
  },
  image: {
    width: 200,
    height: 130,
    resizeMode: 'stretch',
    marginBottom: 10,
  },
  image1: {
    width: 150,
    height: 16,
    resizeMode: 'stretch',
  },
  image2: {
    width: 240,
    height: 18,
    resizeMode: 'stretch',
  },
  inputBox: {
    width: getWidth(80),
    height: 40,
    borderBottomColor: '#A75E5E',
    borderBottomWidth: 1,
  },
  inputBox1: {
    lineHeight: 40,
    color: '#999',
    paddingLeft: 2,
  },
  inputBoxTop: {
    marginTop: 20,
  },
  registerBtn: {
    width: getWidth(50),
    height: 35,
    color: '#fff',
    textAlign: 'center',
    backgroundColor: '#A75E5E',
    marginVertical: 35,
    borderRadius: 35,
    lineHeight: 35,
  },
  centeredView: {
    flex: 1, // 占据了整个页面的宽度，让其子元素居中
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 50,
  },
  modalView: {
    width: getWidth(50),
    height: getHeight(90),
    backgroundColor: 'white',
    borderRadius: 10,
    padding: 35,
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  modalText: {
    marginBottom: 15,
    textAlign: 'center',
  },
  avatarBox: {
    width: windowWidth,
    // height:50,
    padding: 25,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  avatar: {
    color: '#999',
  },
  avatarImage: {
    width:100,
    height:100,
    borderRadius:100,
  }
});
export default connector(Register);


